package com.ytjj.qmyx.mall.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.ytjj.common.constants.CopyWriterConstant;
import com.ytjj.common.constants.QueueConstants;
import com.ytjj.common.constants.SysConfigConstants;
import com.ytjj.common.dto.mqdto.PageStatisticsDto;
import com.ytjj.common.enums.CounponMoneyEnum;
import com.ytjj.common.enums.WxCodeEnums;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.model.UsersResponse;
import com.ytjj.common.model.request.AliyunMallPVRequest;
import com.ytjj.common.model.request.AliyunMallRequest;
import com.ytjj.common.service.WxUtils;
import com.ytjj.common.utils.*;
import com.ytjj.qmyx.mall.constants.VersionConstant;
import com.ytjj.qmyx.mall.enums.BannerStatusEnums;
import com.ytjj.qmyx.mall.enums.PathEnums;
import com.ytjj.qmyx.mall.enums.ProductActivityStatusEnums;
import com.ytjj.qmyx.mall.enums.ProductForumTypeEnums;
import com.ytjj.qmyx.mall.mapper.*;
import com.ytjj.qmyx.mall.model.*;
import com.ytjj.qmyx.mall.model.request.*;
import com.ytjj.qmyx.mall.model.response.*;
import com.ytjj.qmyx.mall.model.vo.ChannelVO;
import com.ytjj.qmyx.mall.service.CommonService;
import com.ytjj.qmyx.mall.utils.AppletsUtil;
import com.ytjj.qmyx.mall.utils.GtPushUtil;
import com.ytjj.qmyx.mall.utils.PathUtils;
import com.ytjj.qmyx.users.client.UsersClient;
import com.ytjj.qmyx.users.model.UserBalanceDto;
import com.ytjj.qmyx.users.model.UsersActiveRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.util.NamedThreadFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 公共接口实现
 *
 *
 * @version 1.0
 *
 */
@Service
@Slf4j
public class CommonServiceImpl implements CommonService {

    @Resource
    private UserBalanceDao userBalanceDao;

    @Resource
    private BannersMapper bannersMapper;

    @Resource
    private RechargeDao rechargeDao;

    @Resource
    private SysConfigMapper sysConfigMapper;

    @Resource
    private PayConfigMapper payConfigMapper;

    @Resource
    private VersionMapper versionMapper;

    @Resource
    private FeedbackMapper feedbackMapper;

    @Resource
    private UsersAnalysisMapper usersAnalysisMapper;

    @Resource
    private ExtraAnalysisMapper extraAnalysisMapper;

    @Resource
    private PathConfigMapper pathConfigMapper;

    @Resource
    private ProductImgMapper productImgMapper;

    @Resource
    private ProductMapper productMapper;

    @Resource
    private ProductActivityImgMapper productActivityImgMapper;

    @Resource
    private ProductActivityMapper productActivityMapper;

    @Resource
    private DynamicMapper dynamicMapper;
    @Resource
    private CopyWriterConfigUtil copyWriterConfigUtil;

    @Resource
    private PageButtonMapper pageButtonMapper;

    @Resource
    private UsersClient usersClient;

    @Resource
    private PushUsersMapper pushUsersMapper;

    @Resource
    private GtPushUtil gtPushUtil;

    @Resource
    CustomerCollectMapper customerCollectMapper;

    @Autowired
    private SysConfigUtil sysConfigUtil;

    @Resource
    private ProductForumDao productForumDao;

    @Resource
    private BankerSiteDao bankerSiteDao;

    @Autowired(required = false)
    private ProductDao productDao;

    @Resource
    private ChannelDao channelDao;

    @Override
    public List<BannersResponse> getBannersListByType(String type) {
        BannersExample example = new BannersExample();
        example.setOrderByClause("sort asc");
        BannersExample.Criteria criteria = example.createCriteria()
                .andTypeEqualTo(type)
                .andStatusEqualTo(BannerStatusEnums.SHOW.getValue());
        List<Banners> banners = bannersMapper.selectByExample(example);
        if ("v3".equals(TokenUtil.getRequest().getHeader("api-ver"))) {
            banners = banners.stream().map(item -> {
                item.setAPath(PathUtils.replaceUrl(item.getAPath()));
                return item;
            })
                    .collect(Collectors.toList());
        }
        return Optional.ofNullable(banners.stream()
                .map(BannersResponse::new)
                .collect(Collectors.toList())).orElse(new ArrayList<>());
    }

    @Override
    public BannersResponse getBannersInfoByType(String type) {
        BannersExample bannersExample = new BannersExample();
        bannersExample.createCriteria()
                .andTypeEqualTo(type)
                .andStatusEqualTo(BannerStatusEnums.SHOW.getValue());
        List<Banners> banners = bannersMapper.selectByExample(bannersExample);
        if ("v3".equals(TokenUtil.getRequest().getHeader("api-ver"))) {
            banners = banners.stream().map(item -> {
                item.setAPath(PathUtils.replaceUrl(item.getAPath()));
                return item;
            })
                    .collect(Collectors.toList());
        }
        return new BannersResponse(banners.get(0));
    }

    @Override
    public String getSysConfigValue(String key) {
        return Optional.ofNullable(sysConfigMapper.selectByPrimaryKey(key))
                .orElseThrow(() -> new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.CONFIGURATION_ITEM_NOTHINGNESS))).getParamValue();
    }

    @Resource
    private VersionsDao versionsDao;

    @Override
    public VersionResponse getVersion(String type, String versionNo) {
        List<Version> versionList = versionsDao.queryHistoryListByType(type);
        if (CollectionUtils.isEmpty(versionList)) {
            VersionResponse result = new VersionResponse();
            result.setForceUpdate((byte)2);
            return result;
        }

        List<Version> newVersionList = new ArrayList<>();
        versionList.stream().forEach(item -> {
            Integer versionNum = Integer.parseInt(versionNo);
            if (Integer.parseInt(item.getVersionNo()) > versionNum) {
                newVersionList.add(item);
            }
        });
        if (CollectionUtils.isEmpty(newVersionList)) {
            VersionResponse result = new VersionResponse();
            result.setForceUpdate((byte)2);
            return result;
        }
        List<Version> forceList = newVersionList.stream().filter(s -> s.getForceUpdate() == 1).collect(Collectors.toList());
        Version version = null;
        VersionResponse response = new VersionResponse();
        if (!CollectionUtils.isEmpty(forceList)) {
//            forceList = forceList.stream().sorted(Comparator.comparing(Version::getVersionNo).reversed()).collect(Collectors.toList());
//            version = forceList.get(0);
            response.setForceUpdate((byte)1);
        }else {
//            version = newVersionList.get(0);
            response.setForceUpdate((byte)0);
        }
        Version maxVersion = newVersionList.get(0);
        response.setDownloadUrl(maxVersion.getUrl());
        response.setPackageType(maxVersion.getPackageType());
        response.setType(maxVersion.getType());
        response.setVersionCode(maxVersion.getVersionNo());
        response.setVersionInfo(maxVersion.getVersionInfo());//1.我们加班做出来的东西你不来支持下吗；\n2.确认不来支持吗；\n3.真不来呀
        response.setVersionName(maxVersion.getVersion());
        return response;
    }

    @Override
    public Map<String, VersionResponse> getVersionsInfo(String type, String versionStr) {
        String channel = TokenUtil.getRequest().getHeader("channel");
        VersionResponse versionResponse;
        // 如果没有版本号，更新到最新的全量包
        if (StringUtils.isBlank(versionStr)) {
            Version version = versionsDao.queryVersionsListByType(type);
            versionResponse = new VersionResponse()
                    .setVersionName(version.getVersion())
                    .setVersionCode(version.getVersion())
                    .setType(version.getType())
                    .setPackageType(version.getPackageType())
                    .setForceUpdate(version.getForceUpdate())
                    .setVersionInfo("")
                    .setDownloadUrl(version.getUrl());
        } else {
            // 如果有版本号，判断是否为最新的版本
            Version version = versionsDao.queryVersionsListByType(type);
            if (versionStr.equals(version.getVersion())) {
                // 如果是最新的版本，返回当前版本
                versionResponse = new VersionResponse()
                        .setVersionName(version.getVersion())
                        .setVersionCode(version.getVersion())
                        .setType(version.getType())
                        .setPackageType(version.getPackageType())
                        .setForceUpdate(version.getForceUpdate())
                        .setVersionInfo("")
                        .setDownloadUrl(version.getUrl());
            } else {
                // 如果不是最新的版本，
                Version versionNew = versionsDao.queryVersionsListByTypeNew(type);
                Integer versionInt = Integer.valueOf(versionStr.replace(".", ""));
                // 判断是否版本号是否大于最新的全量包，
                Boolean b = false;
                try {
                    b = versionInt.intValue() >= Integer.valueOf(versionNew.getVersionNo()).intValue();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (b) {
                    // 大于，返回最新版本号
                    versionResponse = new VersionResponse()
                            .setVersionName(version.getVersion())
                            .setVersionCode(version.getVersion())
                            .setType(version.getType())
                            .setPackageType(version.getPackageType())
                            .setForceUpdate(version.getForceUpdate())
                            .setVersionInfo("")
                            .setDownloadUrl(version.getUrl());
                } else {
                    // 小于，返回最新的全量包
                    versionResponse = new VersionResponse()
                            .setVersionName(versionNew.getVersion())
                            .setVersionCode(versionNew.getVersion())
                            .setPackageType(versionNew.getPackageType())
                            .setType(versionNew.getType())
                            .setForceUpdate(versionNew.getForceUpdate())
                            .setVersionInfo("")
                            .setDownloadUrl(versionNew.getUrl());

                }

            }
        }

        if (StringUtils.isBlank(channel)) {
            channel = "wu";
        }
        log.debug("==========> {} , ======>{}", type, versionStr);
        log.debug("==========> {}", JSONObject.toJSONString(versionResponse));
        if ("hot".equals(versionResponse.getPackageType())) {
            return Stream.of(versionResponse)
                    .collect(Collectors.toMap(item -> VersionConstant.ANDIOS, item -> item));
        }
        versionResponse.setDownloadUrl(versionResponse.getDownloadUrl()
                .replace("CHANNEL", channel));
        return Stream.of(versionResponse)
                .collect(Collectors.toMap(item -> VersionConstant.ANDIOS, item -> item));


//        Version version = versionMapper.selectByPrimaryType(type);
//        Optional.ofNullable(version)
//                .orElseThrow(() -> new ApiException("没有该版本号"));
//        VersionResponse versionResponse = new VersionResponse()
//                .setVersionName(version.getVersion())
//                .setVersionCode(version.getVersion())
//                .setType(version.getType())
//                .setForceUpdate(version.getForceUpdate())
//                .setVersionInfo("")
//                .setDownloadUrl(version.getUrl());
//        return Stream.of(versionResponse)
//                .collect(Collectors.toMap(item -> VersionConstant.ANDIOS, item -> item));
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitIdea(FeedbackRequest feedbackRequest) {
        if (SensitiveWordUtil.contains(feedbackRequest.getContent())) {
            throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.SENSITIVE_WORDS));
        }
        JSONObject jsonObject = WxUtils.msgSecCheck(this.getSysConfigValue(SysConfigConstants.WX_TOKEN), feedbackRequest.getContent());
        if (WxCodeEnums.CODE_87014.getCode().equals(jsonObject.getInteger("errCode"))) {
            throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.SENSITIVE_WORDS));
        }

        Feedback feedback = new Feedback()
                .setUserId(feedbackRequest.getUserId())
                .setSource(feedbackRequest.getSource())
                .setContent(feedbackRequest.getContent())
                .setCreateTime(new Date());
        feedbackMapper.insertSelective(feedback);
    }

    @Resource
    RabbitTemplate rabbitTemplate;

    Executor pools = new ThreadPoolExecutor(5, 10, 5,
            TimeUnit.SECONDS, new LinkedBlockingQueue<>(1024 * 1024),
            new NamedThreadFactory("page_statistics_queue_common"),
            new ThreadPoolExecutor.DiscardOldestPolicy());
    @Override
    public void saveAnalysisData(UsersAnalysisRequest usersAnalysisRequest, UsersResponse usersResponse) {

        String dataJson = usersAnalysisRequest.getDataJson();
        JSONObject object = JSONObject.parseObject(dataJson);
        String model = object.getString("model");                     // 机型
        String fromPage = object.getString("fromPage");             // 现在的页面
        if (fromPage.contains("?")) {
            fromPage = fromPage.substring(0, fromPage.indexOf("?"));
        }
        PathConfig fromPathConfig = this.getPathCodeByUrl(fromPage);
        String fromPageCode = null;
        if (fromPathConfig != null) {
            fromPageCode = fromPathConfig.getPathCode();
        }
        String toPage = object.getString("toPage");                 // 去的页面
        if (toPage.contains("?")) {
            toPage = toPage.substring(0, toPage.indexOf("?"));
        }
        PathConfig toPathConfig = this.getPathCodeByUrl(toPage);
        String toPageCode = null;
        if (toPathConfig != null) {
            toPageCode = toPathConfig.getPathCode();
        }
        String param = object.getString("param");                   // 参数
        String platform = TokenUtil.getRequest().getHeader("source");  // 平台
        String version = TokenUtil.getRequest().getHeader("version");   // 版本
        String channel = "";
        if ("ios".equals(platform) || "weapp".equals(platform)) {
            channel = platform;
        } else {
            channel = TokenUtil.getRequest().getHeader("channel");   // 渠道
        }
        String uuid = object.getString("uuid");                     // uuid
        Integer userId = null;
        String userTel = "";
        if (usersResponse != null && usersResponse.getId()!=null) {
            userId = usersResponse.getId();                     // 用户id
            userTel = usersResponse.getTel();                   // 用户手机号
        }
        PageStatisticsDto pageStatisticsDto = new PageStatisticsDto();
        HttpServletRequest request = TokenUtil.getRequest();
        Integer userActive = 1;
        try {
            String ip = IPUtil.getIpAddress(TokenUtil.getRequest());            // ip
            // 查询yx_users_active表信息
            UsersActiveRequest usersActiveRequest = new UsersActiveRequest();
            usersActiveRequest.setIp(ip);
            usersActiveRequest.setChannel(channel);
            usersActiveRequest.setModel(model);
            usersActiveRequest.setPlatform(platform);
            usersActiveRequest.setUserId(userId);
            usersActiveRequest.setUuid(uuid==null?request.getHeader("uuid"):uuid);
            usersActiveRequest.setUserTel(userTel);
            userActive = usersClient.getUserActive(usersActiveRequest);
        }catch (Exception e){
            log.error("保存userActive错误,channel={},uuid={},dataJson={},{}",channel,uuid,dataJson,e);
        }
        pageStatisticsDto.setUuid(request.getHeader("uuid"));
        pageStatisticsDto.setChannel(TokenUtil.getChannel());
        pageStatisticsDto.setModel(model);
        pageStatisticsDto.setIp(IPUtil.getIpAddress(request));
        pageStatisticsDto.setFromPage(fromPage);
        pageStatisticsDto.setToPage(toPage);
        pageStatisticsDto.setParam(param);
        pageStatisticsDto.setPlatform(TokenUtil.getSource());
        pageStatisticsDto.setCreateTime(new Date());
        pageStatisticsDto.setIsNewUser(userActive);

        //阿里云推送数据
        String batchName = TokenUtil.getRequest().getHeader("batchName");
        AliyunMallPVRequest aliyunMallPVRequestRequest = new AliyunMallPVRequest();
        aliyunMallPVRequestRequest.setBatchName(batchName);
        aliyunMallPVRequestRequest.setChannelCode(channel);
        aliyunMallPVRequestRequest.setCreateTime(DateTimeUtil.getTime());
//        log.info("toPage,{},{},{},{}",toPage,"/pages/integral/mall.html".equals(toPage),toPageCode,"SCORE_SHOP".equals(toPageCode));
        if ("SCORE_SHOP".equals(toPageCode)){
            aliyunMallPVRequestRequest.setOperationNode("1");
        }
        if ("SCORE_PRODUCT_DETAIL".equals(toPageCode)){
            aliyunMallPVRequestRequest.setOperationNode("2");
        }
        aliyunMallPVRequestRequest.setToken(uuid==null?request.getHeader("uuid"):uuid);

        pools.execute(() -> {
            rabbitTemplate.convertAndSend(QueueConstants.PAGE_STATISTICS_QUEUE, pageStatisticsDto);

            try {
                log.info("aliyunMallPVRequestRequest,{}", JSON.toJSONString(aliyunMallPVRequestRequest));
                if (StringUtils.isNotBlank(aliyunMallPVRequestRequest.getOperationNode())){
                    AliyunMallApiUtil.pvPush(aliyunMallPVRequestRequest);
                }
            } catch (Exception e) {
                log.error("埋点数据推送阿里云失败", e);
            }
        });


    }

    @Override
    public void extraAnalysisData(ExtraAnalysisRequest extraAnalysisRequest, String channel) {
        ExtraAnalysis extraAnalysis = new ExtraAnalysis();
        extraAnalysis.setType(extraAnalysisRequest.getType());
        extraAnalysis.setUuid(TokenUtil.getRequest().getHeader("uuid"));
        extraAnalysis.setProductId(extraAnalysisRequest.getProductId());
        String platform = TokenUtil.getRequest().getHeader("source");  // 平台
        String channelVel = "";
        if ("ios".equals(platform) || "weapp".equals(platform)) {
            channelVel = platform;
        } else {
            channelVel = TokenUtil.getRequest().getHeader("channel");   // 渠道
            if (channelVel == null) {
                channelVel = channel;
            }
        }
        extraAnalysis.setChannel(channelVel);
        extraAnalysis.setSource(platform);
        extraAnalysis.setCreateTime(new Date());
        extraAnalysisMapper.insert(extraAnalysis);
    }

    @Override
    public ShareInfoResponse shareInfo(String path, String param) {
        ShareInfoResponse data = new ShareInfoResponse();
        // pages 路径
        String url = path;

        PathConfig pathConfig = this.getPathCodeByUrl(url);

        String pathCode = pathConfig.getPathCode();
        String imgUrl = pathConfig.getImgUrl();
        String shareText = pathConfig.getShareText();

        if (PathEnums.NORMAL_DETAIL.name().equals(pathCode)) {
            // 正常商品详情
            if (StringUtils.isBlank(param)) {
                throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.PARAMETER_NOT_NULL));
            }
            JSONObject jsonObject = JSONObject.parseObject(param);
            Integer productId = jsonObject.getInteger("id");
            ProductImgExample productImgExample = new ProductImgExample();
            productImgExample.createCriteria().andProductIdEqualTo(productId).andTypeEqualTo("banner");
            ProductImg productImg = productImgMapper.selectByExample(productImgExample).get(0);
            data.setImg(productImg.getImgUrl());
            Product product = productMapper.selectByPrimaryKey(productId);
            data.setShareText(product.getProductName());
        } else if (PathEnums.ACTIVITY_DETAIL.name().equals(pathCode)) {
            // 活动商品详情
            if (StringUtils.isBlank(param)) {
                throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.PARAMETER_NOT_NULL));
            }
            JSONObject jsonObject = JSONObject.parseObject(param);
            Integer productId = jsonObject.getInteger("id");
            ProductActivityImgExample productActivityImgExample = new ProductActivityImgExample();
            productActivityImgExample.createCriteria().andProductIdEqualTo(productId).andTypeEqualTo("banner");
            ProductActivityImg productActivityImg = productActivityImgMapper.selectByExample(productActivityImgExample).get(0);
            data.setImg(productActivityImg.getImgUrl());
            ProductActivity productActivity = productActivityMapper.selectByPrimaryKey(productId);
            data.setShareText(productActivity.getProductName());
        } else if (PathEnums.DYNAMIC_DETAIL.name().equals(pathCode)) {
            // 动态
            if (StringUtils.isBlank(param)) {
                throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.PARAMETER_NOT_NULL));
            }
            JSONObject jsonObject = JSONObject.parseObject(param);
            Integer dynamicId = jsonObject.getInteger("dynamicId");
            Dynamic dynamic = dynamicMapper.selectByPrimaryKey(dynamicId);
            data.setImg(dynamic.getImg());
            data.setShareText(dynamic.getTitle());
        } else {
            data.setImg(imgUrl);
            data.setShareText(shareText);
        }

        return data;
    }

    private PathConfig getPathCodeByUrl(String path) {
        PathConfigExample pathConfigExample = new PathConfigExample();
        pathConfigExample.createCriteria().andPathEqualTo(path);
        List<PathConfig> list = pathConfigMapper.selectByExample(pathConfigExample);
        if (!CollectionUtils.isEmpty(list)) {
            return list.get(0);
        }
        return null;
    }

    /**
     * 获取pageButton
     *
     * @param activityType
     * @return
     */
    @Override
    public PageButton getPageButton(String activityType, String type) {
        PageButtonExample pageButtonExample = new PageButtonExample();
        pageButtonExample.createCriteria()
                .andActivityTypeEqualTo(activityType)
                .andTypeEqualTo(type);
        List<PageButton> pageButtons = pageButtonMapper.selectByExample(pageButtonExample);
        if (pageButtons.size() > 0) {
            return pageButtons.get(0);
        }
        return null;
    }

    @Override
    public Map<String, Object> getWxConfigure() {
        Map<String, Object> param = new HashMap<>();
        // 系统配置
        SysConfigExample sysConfigExample = new SysConfigExample();
        List<SysConfig> sysConfigs = sysConfigMapper.selectByExample(sysConfigExample);
        sysConfigs.stream().forEach(item -> {
            param.put(item.getParamKey(), item.getParamValue());
        });
        // 支付配置
        PayConfigExample payConfigExample = new PayConfigExample();
        payConfigExample.createCriteria().andTypeEqualTo("H5").andTradeTypeEqualTo("JSAPI");
        List<PayConfig> payConfigs = payConfigMapper.selectByExample(payConfigExample);
        if (!CollectionUtils.isEmpty(payConfigs)) {
            PayConfig payConfig = payConfigs.get(0);
            param.put("PAY_CONFIG_TOKEN", payConfig.getToken());
            param.put("PAY_CONFIG_TICKET", payConfig.getTicket());
        }
        return param;
    }

    @Override
    public Map<String, Object> gtPushInfoByCid(GtPushRequest gtPushRequest) {
        if (StringUtils.isBlank(gtPushRequest.getCid())) {
            throw new ApiException("cid不能为空！");
        }
        // 商品详情
        if ("PRODUCT_DETAIL".equals(gtPushRequest.getType())) {
            Integer dataId = gtPushRequest.getDataId();
            if (dataId != null) {
                Product product = productMapper.selectByPrimaryKey(dataId);
                // 推送
                Map<String, Object> param = new HashMap<>();
                param.put("url", gtPushRequest.getUrl());
                param.put("title", product.getProductName());
                param.put("content", product.getDescr());
                param.put("icon", product.getProductImg());
                Map<String, Object> stringObjectMap = gtPushUtil.pushMessage(gtPushRequest.getCid(), param);
                return stringObjectMap;
            }
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void getCidInfo(CidInfoRequest cidInfoRequest, UsersResponse usersResponse) {
        PushUsersExample pushUsersExample = new PushUsersExample();
        pushUsersExample.createCriteria().andUserIdEqualTo(usersResponse.getId());
        List<PushUsers> pushUsersList = pushUsersMapper.selectByExample(pushUsersExample);
        PushUsers pushUsers = null;
        if (CollectionUtils.isEmpty(pushUsersList)) {
            pushUsers = new PushUsers();
            pushUsers.setCid(cidInfoRequest.getCid());
            // uuid
            String uuid = TokenUtil.getRequest().getHeader("uuid");
            pushUsers.setUuid(uuid);
            // 渠道
            String channel = TokenUtil.getRequest().getHeader("channel");
            pushUsers.setChannel(channel);
            // 来源
            String source = TokenUtil.getRequest().getHeader("source");
            pushUsers.setSource(source);
            // 机型
            String extInfo = TokenUtil.getRequest().getHeader("extInfo");
            if (StringUtils.isNotBlank(extInfo)) {
                HashMap hashMap = JSONObject.parseObject(extInfo, HashMap.class);
                if (hashMap != null) {
                    pushUsers.setBrand(hashMap.get("brand").toString());
                    pushUsers.setModel(hashMap.get("model").toString());
                }
            }
            pushUsers.setCreateTime(new Date());
            if (usersResponse != null) {
                pushUsers.setUserId(usersResponse.getId());
            }
            pushUsersMapper.insert(pushUsers);
        } else {
            pushUsers = pushUsersList.get(0);
            pushUsers.setCid(cidInfoRequest.getCid());
            // uuid
            String uuid = TokenUtil.getRequest().getHeader("uuid");
            pushUsers.setUuid(uuid);
            // 渠道
            String channel = TokenUtil.getRequest().getHeader("channel");
            pushUsers.setChannel(channel);
            // 来源
            String source = TokenUtil.getRequest().getHeader("source");
            pushUsers.setSource(source);
            // 机型
            String extInfo = TokenUtil.getRequest().getHeader("extInfo");
            if (StringUtils.isNotBlank(extInfo)) {
                HashMap hashMap = JSONObject.parseObject(extInfo, HashMap.class);
                if (hashMap != null) {
                    pushUsers.setBrand(hashMap.get("brand").toString());
                    pushUsers.setModel(hashMap.get("model").toString());
                }
            }
            pushUsers.setUpdateTime(new Date());
            if (usersResponse != null) {
                pushUsers.setUserId(usersResponse.getId());
            }
            pushUsersMapper.updateByPrimaryKey(pushUsers);

        }
    }

    @Override
    public void getCustomerCollect(CustomerCollectRequest customerCollectRequest) {
        CustomerCollect customerCollect = new CustomerCollect();
        customerCollect.setToken(TokenUtil.getToken());
        customerCollect.setUuid(TokenUtil.getRequest().getHeader("uuid"));
        customerCollect.setTel(customerCollectRequest.getTel());
        customerCollect.setChannel(TokenUtil.getChannel());
        customerCollect.setContent(customerCollectRequest.getContent());
        customerCollect.setCreateTime(new Date());
        customerCollectMapper.insert(customerCollect);
    }

    @Resource
    private PhoneRechargeConfigMapper phoneRechargeConfigMapper;

    @Resource
    private PhoneRechargeMapper phoneRechargeMapper;

    @Override
    public List<PhoneRechargeConfig> getPhoneChargesList() {
        return phoneRechargeConfigMapper.selectByExample(new PhoneRechargeConfigExample())
                .stream().map(item -> {
                    item.setPrice(item.getPrice() / 100);
                    return item;
                }).collect(Collectors.toList());
    }


    @Override
    public List<PhoneRecharge> rechargeList() {
        List<PhoneRecharge> phoneRecharges = rechargeDao.findByToken(TokenUtil.getToken());
        return phoneRecharges.stream()
                .map(item -> {
                    item.setPrice(item.getPrice() / 100);
                    if (item.getRechargeStatus() != null && item.getRechargeStatus() == 1) {
                        item.setStatus(5);                  // 充值成功
                    }
                    return item;
                })
                .collect(Collectors.toList());
    }

    @Resource
    private ForumLiveMapper forumLiveMapper;
    @Resource
    private ForumLiveInfoDao forumLiveInfoDao;

    @Override
    public ForumLiveResponse getforumLiveData() {
        ForumLiveResponse forumLiveResponse = new ForumLiveResponse();
        List<Map<String, Object>> result = new ArrayList<>();

        ForumLiveExample forumLiveExample = new ForumLiveExample();
        forumLiveExample.setOrderByClause("sort asc");
        forumLiveExample.createCriteria()
                .andStatusEqualTo(1);
        List<ForumLive> forumLive = forumLiveMapper.selectByExample(forumLiveExample);
        forumLive.forEach(item -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", item.getId());
            map.put("title", item.getTitle());
            map.put("img", item.getImg());
            PageHelper.startPage(1,18);
            List<Product> infos = forumLiveInfoDao.selectForumProducts(item.getId());
            map.put("infos", infos);
            result.add(map);
        });
        String type = "LIFE_HOUSE_BACKGROUND";
        // 背景信息
        BannersExample bannersExample = new BannersExample();
        bannersExample.createCriteria()
                .andTypeEqualTo(type)
                .andStatusEqualTo((byte) 1);
        List<Banners> bannersList = bannersMapper.selectByExample(bannersExample);
        if (CollectionUtils.isEmpty(bannersList)) {
            throw new ApiException("bannner表未配置type：" + type);
        }
        forumLiveResponse.setBackground(bannersList.get(0).getImgUrl());
        forumLiveResponse.setColor(bannersList.get(0).getBackgroundColor());
        forumLiveResponse.setLiveInfoList(result);
        return forumLiveResponse;
    }

    @Override
    public ForumLiveResponse getH5ForumLiveData() {
        ForumLiveResponse forumLiveResponse = new ForumLiveResponse();
        List<Map<String, Object>> result = new ArrayList<>();

        ForumLiveExample forumLiveExample = new ForumLiveExample();
        forumLiveExample.setOrderByClause("sort asc");
        forumLiveExample.createCriteria()
                .andStatusEqualTo(1);
        List<ForumLive> forumLive = forumLiveMapper.selectByExample(forumLiveExample);
        forumLive.forEach(item -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", item.getId());
            map.put("title", item.getTitle());
            map.put("img", item.getImg());
            PageHelper.startPage(1,18);
            List<Product> infos = forumLiveInfoDao.selectH5ForumProducts(item.getId());
            map.put("infos", infos);
            result.add(map);
        });
        String type = "LIFE_HOUSE_BACKGROUND";
        // 背景信息
        BannersExample bannersExample = new BannersExample();
        bannersExample.createCriteria()
                .andTypeEqualTo(type)
                .andStatusEqualTo((byte) 1);
        List<Banners> bannersList = bannersMapper.selectByExample(bannersExample);
        if (CollectionUtils.isEmpty(bannersList)) {
            throw new ApiException("bannner表未配置type：" + type);
        }
        forumLiveResponse.setBackground(bannersList.get(0).getImgUrl());
        forumLiveResponse.setColor(bannersList.get(0).getBackgroundColor());
        forumLiveResponse.setLiveInfoList(result);
        return forumLiveResponse;
    }

    /**
     * 首页秒杀
     *
     * @return
     */
    @Override
    public SeckillDataResponse querySeckillData() {
        SeckillDataResponse seckillDataResponse = new SeckillDataResponse();
        List<Product> products = productForumDao.queryProductForum(ProductForumTypeEnums.SECKILL.name(), TokenUtil.getPlatformData());
        if (!CollectionUtils.isEmpty(products)) {
            Product product = products.get(0);
            // 秒杀顶部商品
            seckillDataResponse.setTopProduct(product);
            int num = 1;
            if (products.size() > num) {
                List<Product> productList = products.subList(num, products.size());
                List<ProductResponse> productResponseList = productList.stream().map(ProductResponse::new)
                        .collect(Collectors.toList());
                // 秒杀列表商品
                seckillDataResponse.setProductList(productResponseList);
            }
        }
        return seckillDataResponse;
    }

    @Override
    public List<ProductResponse> querySeckillList() {
        List<Product> productList = productForumDao.queryProductSkill("SECKILL", TokenUtil.getPlatformData());
        List<ProductResponse> productResponsetList = productList.stream()
                .map(ProductResponse::new)
                .collect(Collectors.toList());
        return productResponsetList;
    }

    @Override
    public List<ProductResponse> queryNewProductList() {
        List<Product> productList = productForumDao.queryProductForum(ProductForumTypeEnums.NEW_RECOMMEND.name(), TokenUtil.getPlatformData());
        List<ProductResponse> productResponsetList = productList.stream()
                .map(ProductResponse::new)
                .collect(Collectors.toList());
        return productResponsetList;
    }

    /**
     * 首页积分
     *
     * @return
     */
    @Override
    public List<ProductResponse> queryCashScoreList() {
        List<Product> productList = productForumDao.queryScoreProductForum(TokenUtil.getPlatformData());
//        List<Product> productList = productForumDao.queryProductForum(ProductForumTypeEnums.CASH_SCORE.name(),TokenUtil.getPlatformData());
        List<ProductResponse> productResponsetList = productList.stream()
                .map(ProductResponse::new)
                .collect(Collectors.toList());
        return productResponsetList;
    }

    @Override
    public List<ProductResponse> queryOldForNewList() {
        List<Product> productList = productForumDao.queryProductForum(ProductForumTypeEnums.OLD_FOR_NEW.name(), TokenUtil.getPlatformData());
        List<ProductResponse> productResponsetList = productList.stream()
                .map(ProductResponse::new)
                .collect(Collectors.toList());
        return productResponsetList;
    }

    @Resource
    private BankerSiteMapper bankerSiteMapper;

    @Override
    public List<BrandProductResponse> queryBrandProductList() {

        List<BrandProductResponse> brandProductList = new ArrayList<>();
        List<ProductForum> productForumList = productForumDao.queryBrandList(ProductForumTypeEnums.BRAND_SHOP.name());
        productForumList.stream().forEach(item -> {
            BankerSiteExample bankerSiteExample = new BankerSiteExample();
            bankerSiteExample.createCriteria()
                    .andBankerIdEqualTo(item.getProductId())
                    .andStatusEqualTo(1);
            List<BankerSite> bankerSites = bankerSiteMapper.selectByExample(bankerSiteExample);
            if (!CollectionUtils.isEmpty(bankerSites)) {
                BankerSite bankerSite = bankerSites.get(0);
                BrandProductResponse brandProductResponse = new BrandProductResponse();
                brandProductResponse.setBankerId(bankerSite.getBankerId());
                brandProductResponse.setLogo(bankerSite.getLogo());
                brandProductResponse.setLongTitle(bankerSite.getLongTitle());
                brandProductResponse.setTitle(bankerSite.getTitle());
                List<Product> products = productForumDao.queryBrandProductList(item.getId(), TokenUtil.getPlatformData());
                List<ProductResponse> productResponse = products.stream()
                        .map(ProductResponse::new)
                        .collect(Collectors.toList());
                brandProductResponse.setProductList(productResponse);

                brandProductList.add(brandProductResponse);
            }
        });
        return brandProductList;
    }

    // 字符串数组转整数集合
    private List<Integer> convertType(String config) {
        String[] str = config.split(",");
        List<Integer> ids = new ArrayList<>();
        for (int i = 0; i < str.length; i++) {
            ids.add(Integer.parseInt(str[i]));
        }
        return ids;
    }

    /**
     * 0元测评商品
     *
     * @return
     */
    @Override
    public List<ProductResponse> queryZeroProductList() {
        List<Product> productList = productForumDao.queryProductForum(ProductForumTypeEnums.ZERO_EVALUATION.name(), TokenUtil.getPlatformData());
        List<ProductResponse> productResponsetList = productList.stream()
                .map(item -> {
                    ProductResponse productResponse = new ProductResponse(item);// 0元测评用stock_evaluation代替stock
                    productResponse.setStock(item.getStockEvaluation());
                    return productResponse;
                })
                .collect(Collectors.toList());
        return productResponsetList;
    }

    @Override
    public List<ProductResponse> queryCashCouponList() {
        List<Product> productList = productForumDao.queryProductForum(ProductForumTypeEnums.CASH_COUPON.name(), TokenUtil.getPlatformData());
        List<ProductResponse> productResponsetList = productList.stream()
                .map(ProductResponse::new)
                .collect(Collectors.toList());
        return productResponsetList;
    }

    @Override
    public PickUpLeakResponse queryPickUpLeak() {
        PickUpLeakResponse pickUpLeakResponse = new PickUpLeakResponse();
        List<Product> productList = productForumDao.queryProductForum(ProductForumTypeEnums.PICK_UP_LEAK.name(), TokenUtil.getPlatformData());
        List<ProductResponse> productResponsetList = productList.stream()
                .map(ProductResponse::new)
                .collect(Collectors.toList());
        pickUpLeakResponse.setPickUpLeakList(productResponsetList);
        pickUpLeakResponse.setProductId(Integer.parseInt(sysConfigUtil.getSysConfig("PICKUPLEAK_PRODUCTID")));
        return pickUpLeakResponse;
    }

    @Override
    public List<FakeUserAndImg> getFakeUsersAndImg(List<Object> fakeUserList, Long number) {
        List<UsersFake> usersFake = fakeUserList.stream()
                .map(item -> JSONObject.parseObject((String) item, UsersFake.class))
                .collect(Collectors.toList());

        List<FakeUserAndImg> collect = usersFake.stream()
                .map(item -> {
                    List<String> imgs = usersFake.stream()
                            .map(i -> i.getHeadImg())
                            .collect(Collectors.toList());
                    Collections.shuffle(imgs);
                    imgs = imgs.stream().limit(number).collect(Collectors.toList());
                    FakeUserAndImg fakeUserAndImg = new FakeUserAndImg();
                    fakeUserAndImg.setName(item.getNickname());
                    fakeUserAndImg.setImg(imgs);
                    return fakeUserAndImg;
                })
                .collect(Collectors.toList());
        return collect;
    }

    @Override
    public List<FakeUsersAndProduct> getFakeUsersAndProduct(List<Object> fakeUserList) {
        List<UsersFake> usersFake = fakeUserList.stream()
                .map(item -> JSONObject.parseObject((String) item, UsersFake.class))
                .collect(Collectors.toList());

        List<FakeUsersAndProduct> collect = usersFake.stream()
                .map(item -> {
                    FakeUsersAndProduct fakeUsersAndProduct = new FakeUsersAndProduct();
                    fakeUsersAndProduct.setName(item.getNickname());

                    return fakeUsersAndProduct;
                })
                .collect(Collectors.toList());
        return collect;
    }

    @Resource
    private AppletsUtil appletsUtil;

    @Override
    public String skipApplets(String code, String channel, String accessToken, Integer pid) {
        if (StringUtils.isEmpty(code)) {
            throw new ApiException("请传入跳转的路径标识!");
        }
        // 跳转小程序
        JSONObject resultJson = appletsUtil.skipPath(code, channel, accessToken, pid);
        if ("0".equals(resultJson.get("errcode").toString())) {
            String openlink = resultJson.get("openlink").toString();
            return openlink;
        }
        throw new ApiException("跳转小程序异常,请重试!");
    }

    @Override
    public String skipAppletsByPath(String path, String channel, String accessToken) {
        if (StringUtils.isEmpty(path)) {
            throw new ApiException("请传入跳转的路径标识!");
        }
        // 跳转小程序
        JSONObject resultJson = appletsUtil.skipByPath(path, channel, accessToken);
        if ("0".equals(resultJson.get("errcode").toString())) {
            String openlink = resultJson.get("openlink").toString();
            return openlink;
        }
        throw new ApiException("跳转小程序异常,请重试!");
    }

    @Override
    public String skipAppletsByPath(String path, String channel, String query, String accessToken) {
//        if (StringUtils.isEmpty(path)) {
//            throw new ApiException("请传入跳转的路径标识!");
//        }
        String envVersion = null;
        try {
            envVersion = sysConfigUtil.getSysConfig("wx_env_version");
        } catch (Exception e) {
            log.error("wx_env_version错误",e);
        }
        // 跳转小程序
        JSONObject resultJson = appletsUtil.skipByPath(path, channel, query, accessToken,envVersion);
        if ("0".equals(resultJson.get("errcode").toString())) {
            String openlink = resultJson.get("openlink").toString();
            return openlink;
        }
        throw new ApiException("跳转小程序异常,请重试!");
    }


    @Resource
    private ChannelMapper channelMapper;

    @Override
    public Map<String, Object> getInfoByChannel(String channel) {
        Map<String, Object> result = new HashMap<>();
        ChannelExample example = new ChannelExample();
        example.createCriteria()
                .andChannelEqualTo(channel);
        List<Channel> channelList = channelMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(channelList)) {
            result.put("channel", channelList.get(0).getChannel());
            result.put("channelStatus", channelList.get(0).getChannelStatus());
        }
        return result;
    }

    private List<Product> getProductList(String activityType, List<Integer> columnIds, List<Integer> bankerColumnIds) {
        ProductExample productExample = new ProductExample();
        productExample.setOrderByClause("sort desc");
        productExample.createCriteria()
                .andActivityTypeEqualTo(activityType)
                .andIsAdvertEqualTo(0)
                .andIsHideEqualTo(0)
                .andColumnIdIn(columnIds)
                .andBankerColumnIdIn(bankerColumnIds)
                .andPlatformDataIn(Arrays.asList(TokenUtil.getPlatformData(), "all"))
                .andStatusIn(Arrays.asList(ProductActivityStatusEnums.UP.getValue()));
        List<Product> productList = productMapper.selectByExample(productExample);
        return productList;
    }

    @Override
    public String addUserBalance(Integer userId, CounponMoneyEnum type) {
        int count = userBalanceDao.countByUserIdTypeToDay(userId, type);
        log.info("====count==={}", count);
        if (0 != type.getNum() && count >= type.getNum()) return null;
        Random random = new Random();
        BigDecimal addMoney = BigDecimal.ZERO;
        if (CounponMoneyEnum.RELEASE_EVALUATION.equals(type)) {
            addMoney = new BigDecimal((random.nextInt(118)) / 100.0D).setScale(2, BigDecimal.ROUND_HALF_UP);
            if (addMoney.compareTo(new BigDecimal("0.02")) < 0) {
                addMoney = new BigDecimal("0.02");
            }
        }else {
            addMoney = new BigDecimal((random.nextInt(19)) / 100.0D).setScale(2, BigDecimal.ROUND_HALF_UP);
        }
        log.info("===addMoney==={}", addMoney);
//        BigDecimal addMoney = type.equals(CounponMoneyEnum.RELEASE_EVALUATION) ? CounponMoneyEnum.RELEASE_EVALUATION.getMoney() : new BigDecimal((random.nextInt(29) + 2) / 100.0D).setScale(2, BigDecimal.ROUND_HALF_UP);
        UserBalanceDto userBalanceDto = new UserBalanceDto();
        userBalanceDto.setUserId(userId);
        userBalanceDto.setUpdateMoney(addMoney);
        userBalanceDto.setType("ADD");
        userBalanceDto.setSource(type.toString());
        userBalanceDto.setAmountType(1);
        usersClient.updateMoney(userBalanceDto);
        return addMoney.toString();
    }

    @Override
    public String backZeroEvaluationCapitalMoney(Integer userId, CounponMoneyEnum type, BigDecimal money) {
        int count = userBalanceDao.countByUserIdTypeToDay(userId, type);
        log.info("====count==={}", count);
        if (0 != type.getNum() && count >= type.getNum()) return null;
        Random random = new Random();
        BigDecimal addMoney = null == money ? BigDecimal.ZERO : money;
        log.info("===addMoney==={}", addMoney);
        UserBalanceDto userBalanceDto = new UserBalanceDto();
        userBalanceDto.setUserId(userId);
        userBalanceDto.setUpdateMoney(addMoney);
        userBalanceDto.setType("ADD");
        userBalanceDto.setSource(type.toString());
        userBalanceDto.setAmountType(1);
        usersClient.updateMoney(userBalanceDto);
        return addMoney.toString();
    }

    @Override
    public int doGiveScore(Integer userId, CounponMoneyEnum type) {
        Random random = new Random();
        int score = 20 + random.nextInt(4);
        try {
            usersClient.addScore(score, userId, type.name());
        } catch (Exception e) {
            log.error("===用户赠送积分异常==={},{}", userId, score);
        }
        return score;
    }

    @Override
    public Object getCounponList(Integer userId) {
        List<CounponListResponse> list = new ArrayList<>();
        for (CounponMoneyEnum value : CounponMoneyEnum.values()) {
            CounponListResponse counponListResponse = new CounponListResponse();
            counponListResponse.setType(value.toString());
            counponListResponse.setNum(value.getNum());
            int i = userBalanceDao.countByUserIdTypeToDay(userId, value);
            counponListResponse.setCount(i);
            list.add(counponListResponse);
        }
        return list;
    }

    @Override
    public List<BrandListResponse> getBrandPavilionList(Integer pageNum, Integer pageSize, Integer specialId) {
        PageHelper.startPage(pageNum,pageSize);
        List<BrandListResponse> brandListResponses = bankerSiteDao.findBrandListResponse(specialId,specialId == -1 ? 1 : 0);
        if(brandListResponses == null || brandListResponses.size() == 0) {
            return brandListResponses;
        }
        if(specialId == -1) {
            Collections.shuffle(brandListResponses);
        }
        String platformData = TokenUtil.getPlatformData();
        for (BrandListResponse brandListResponse : brandListResponses) {
//            brandListResponse.setCount(productDao.countByBrandId(brandListResponse.getId()));
            brandListResponse.setCount(productDao.queryByBrandIdAndPlatformCount(brandListResponse.getId(), platformData));//根据h5平台来统计
            Random random = new Random();
            int i = random.nextInt(5);
            brandListResponse.setDiscount(BigDecimal.valueOf(i%5 * 0.5 +1.0).setScale(1,BigDecimal.ROUND_HALF_UP).toString());
//            brandListResponse.setBrandProducts(productDao.findListByBrandId(brandListResponse.getId(),9,specialId!=null&&specialId>0?specialId:null));
            brandListResponse.setBrandProducts(productDao.findListByBrandIdAndPlatform(brandListResponse.getId(), 9, specialId != null && specialId > 0 ? specialId : null, platformData));
        }
        return brandListResponses;
    }

    @Override
    public BrandInfoResponse getBrandPavilionInfo(Integer pageNum, Integer pageSize, Integer id, String platformData) {
        BrandInfoResponse brandInfoResponse=new BrandInfoResponse();
        BrandListResponse brandListResponse = bankerSiteDao.findBrandResponse(id);
        if (brandListResponse == null) {
            return null;
        }
        BeanUtils.copyProperties(brandListResponse,brandInfoResponse);
        brandInfoResponse.setCount(productDao.countByBrandIdAndPlatformData(brandListResponse.getId(),platformData));
        Random random = new Random();
        int i = random.nextInt(5);
        brandInfoResponse.setDiscount(BigDecimal.valueOf(i % 5 * 0.5 + 1.0).setScale(1, BigDecimal.ROUND_HALF_UP).toString());
        PageHelper.startPage(pageNum,pageSize);
        brandInfoResponse.setProductActivityList(productDao.findListByBrandIdAndPlatformData(brandListResponse.getId(), null,null,platformData));
        return brandInfoResponse;
    }

    @Override
    public ChannelVO findChannel(String channel) {
        return channelDao.findChannel(channel);
    }

}
